package it.poste.il.compensatore.web.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class CompensatoreHttpClient {
	
	public CompensatoreHttpClient(){
		super();
	}

	public static String sendRequest(String url,String action,String msg) throws ClientProtocolException, IOException{
		HttpClient httpClient=new DefaultHttpClient();
		HttpPost methodPost=new HttpPost(url);
		
		StringEntity entity=null;
		entity = new StringEntity(msg,"UTF-8");
		
		methodPost.setEntity(entity);
				         
	    //setta gli header necessari 		
        methodPost.setHeader("SOAPAction","\""+action+"\"");
        methodPost.setHeader("accept-encoding","gzip,deflate" );
		methodPost.setHeader("Content-Type", "text/xml;charset=UTF-8");  
		
		HttpResponse res=httpClient.execute(methodPost);

		String line = "";     
	    StringBuilder total = new StringBuilder();  
	    // Wrap a BufferedReader around the InputStream 
	        
        //necessario per l'encoding
        GZIPInputStream gzip=new GZIPInputStream(res.getEntity().getContent());
        BufferedReader rd = new BufferedReader(new InputStreamReader(gzip));
        
        // Read response until the end
        while ((line = rd.readLine()) != null) {  
        	total.append(line);
        }

		 System.out.println("ClientResp: "+total);
		 return total.toString();
	}
}
